package com.cindata

import com.cindata.dictionary.*
import grails.converters.JSON
import grails.gorm.transactions.Transactional
import org.springframework.security.access.annotation.Secured


import static org.springframework.http.HttpStatus.*

@Transactional
@Secured(['isAuthenticated()'])
class AccountController
{

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def workflowInstanceService
    def accountService
    def dataSource
    def springSecurityService
    def developerApiService

    // 机构列表页面
    def index()
    {
    }

    /** ------------------------------贷款机构 -----------------------------------**/
    def mortgageAccountIndex()
    {
        def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        def offset = params.offset ? params.offset.toInteger() : 0
        //城市
        def city = params["city"]
        //行政区
        def district = params["district"]
        //注册资金
        def registeredCapitalStart = params["registeredCapitalStart"]
        //注册资金
        def registeredCapitalEnd = params["registeredCapitalEnd"]
        //信用评级
        def creditLevel = params["creditLevel"]
        //企业名称
        def name = params["name"]
        //经营状态
        def operatingState = params["operatingState"]
        //单位性质
        def unitNature = params["unitNature"]
        def estateQueryParam = new HashMap()
        def sort = params["sort"]
        def order = params["order"]

        def user = User.findById(springSecurityService.principal.id)
        def estateSql = " from Account e where e.type.code = 'MortgageAccount' and e.bankAccount.id in " + Account.FilterAccountSql(user)
        def sql = " "
        if (name && name != "")
        {
            sql += " and e.name like :name"
            estateQueryParam['name'] = '%' + name + '%'
        }
        if (city && city != "-1")
        {
            sql += " and e.city.zoneNumber = :city "
            estateQueryParam['city'] = city
        }
        if (district && district != "-1")
        {
            sql += " and e.district.zoneNumber = :district "
            estateQueryParam['district'] = district
        }
        if (registeredCapitalStart && registeredCapitalStart != "")
        {
            sql += "and e.registeredCapital >= :registeredCapitalStart "
            estateQueryParam['registeredCapitalStart'] = new BigDecimal(registeredCapitalStart) * 10000
        }
        if (registeredCapitalEnd && registeredCapitalEnd != "")
        {
            sql += "and e.registeredCapital <= :registeredCapitalEnd "
            estateQueryParam['registeredCapitalEnd'] = new BigDecimal(registeredCapitalEnd) * 10000
        }
        if (creditLevel && creditLevel != "")
        {
            sql += " and e.creditLevel like :creditLevel "
            estateQueryParam['creditLevel'] = "%" + creditLevel + "%"
        }
        if (operatingState && operatingState != "")
        {
            sql += " and e.operatingState = :operatingState "
            estateQueryParam['operatingState'] = operatingState
        }
        if (unitNature && unitNature != "")
        {
            sql += " and e.unitNature.id = :unitNature "
            estateQueryParam['unitNature'] = Long.parseLong(unitNature)
        }

        def countSql = " select count(e.id) from Account e where e.type.code = 'MortgageAccount' and e.bankAccount.id in " + Account.FilterAccountSql(user)
        countSql += sql

        if (order && sort)
        {
            sql += " order by e.${sort} ${order}"
        }
        else
        {
            sql += " order by e.modifiedDate desc "
        }
        estateSql += sql

        def accountList = Account.executeQuery(estateSql, estateQueryParam, [max: max, offset: offset])
        def accountCount = Account.executeQuery(countSql, estateQueryParam)
        respond accountList, model: [accountCount: accountCount[0], params: params], view: 'mortgageAccountIndex'
    }

    def mortgageAccountCreate()
    {
        respond new Account(params)
    }

    @Transactional
    def save(Account account)
    {
        if (account == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (account.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond account.errors, view: 'mortgageAccountCreate'
            return
        }

        account.save flush: true

        def mortgageList = params["mortgageList"]
        if (mortgageList instanceof String)
        {
            mortgageList = mortgageList?.split(",")
        }
        println mortgageList
        mortgageList?.each
        {
            def mortgage = Mortgage.findById(it)
            mortgage.mortgageAccount = account
            mortgage.mortgageCategory = MortgageCategory.findByCode('2')
            if (mortgage.validate()) 
            {
                mortgage.save flush: true
            }
            else
            {
                println mortgage.errors
            }
        }

        redirect action: 'mortgageAccountShow', id: account?.id
    }

    def mortgageAccountEdit(Account account)
    {
        respond account
    }

    @Transactional
    def update(Account account)
    {
        if (account == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (account.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond account.errors, view: 'mortgageAccountEdit'
            return
        }

        account.save flush: true

        def reMortgageList = Mortgage.findAllByMortgageAccountAndMortgageCategory(account, MortgageCategory.findByCode('2'))
        reMortgageList?.each
        {
            it.mortgageAccount = null
            it.save flush: true
        }

        def mortgageList = params["mortgageList"]
        if (mortgageList instanceof String)
        {
            mortgageList = mortgageList?.split(",")
        }
        mortgageList?.each
        {
            def mortgage = Mortgage.findById(it)
            mortgage.mortgageAccount = account
            mortgage.mortgageCategory = MortgageCategory.findByCode('2')
            if (mortgage.validate()) 
            {
                mortgage.save flush: true
            }
            else
            {
                println mortgage.errors
            }
        }


        redirect action: 'mortgageAccountShow', id: account?.id



    }

    def mortgageAccountShow(Account account)
    {
        respond account
    }

    // def bankAccountIndex()
    // {
    //     def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
    //     def offset = params.offset ? params.offset.toInteger() : 0
    //     //城市
    //     def city = params["city"]
    //     //行政区
    //     def district = params["district"]
    //     def name = params["name"]
    //     def address = params["address"]
    //     def estateQueryParam = new HashMap()
    //     def sort = params["sort"]
    //     def order = params["order"]

    //     def user = User.findById(springSecurityService.principal.id)
    //     def estateSql = " from Account e where e.type.code = 'BankAccount' and e.id in " + Account.FilterAccountSql(user)
    //     def sql = " "
    //     if (name && name != "")
    //     {
    //         sql += " and e.name like :name"
    //         estateQueryParam['name'] = '%' + name + '%'
    //     }
    //     if (address && address != "")
    //     {
    //         sql += " and e.address like :address"
    //         estateQueryParam['address'] = '%' + address + '%'
    //     }
    //     if (city && city != "-1")
    //     {
    //         sql += " and e.city.zoneNumber = :city "
    //         estateQueryParam['city'] = city
    //     }
    //     if (district && district != "-1")
    //     {
    //         sql += " and e.district.zoneNumber = :district "
    //         estateQueryParam['district'] = district
    //     }

    //     def countSql = " select count(e.id) from Account e where e.type.code = 'BankAccount' and e.id in " + Account.FilterAccountSql(user)
    //     countSql += sql

    //     if (order && sort)
    //     {
    //         sql += " order by e.${sort} ${order}"
    //     }
    //     else
    //     {
    //         sql += " order by e.modifiedDate desc "
    //     }
    //     estateSql += sql

    //     def accountList = Account.executeQuery(estateSql, estateQueryParam, [max: max, offset: offset])
    //     def accountCount = Account.executeQuery(countSql, estateQueryParam)
    //     respond accountList, model: [accountCount: accountCount[0], params: params], view: 'bankAccountIndex'
    // }

    // def evaluateAccountIndex()
    // {
    //     def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
    //     def offset = params.offset ? params.offset.toInteger() : 0
    //     //城市
    //     def city = params["city"]
    //     //行政区
    //     def district = params["district"]
    //     def name = params["name"]
    //     def address = params["address"]
    //     def estateQueryParam = new HashMap()
    //     def sort = params["sort"]
    //     def order = params["order"]

    //     def user = User.findById(springSecurityService.principal.id)
    //     def estateSql = " from Account e where e.type.code = 'EvaluateAccount' and e.bankAccount in " + Account.FilterAccountSql(user)
    //     def sql = " "
    //     if (name && name != "")
    //     {
    //         sql += " and e.name like :name"
    //         estateQueryParam['name'] = '%' + name + '%'
    //     }
    //     if (address && address != "")
    //     {
    //         sql += " and e.address like :address"
    //         estateQueryParam['address'] = '%' + address + '%'
    //     }
    //     if (city && city != "-1")
    //     {
    //         sql += " and e.city.zoneNumber = :city "
    //         estateQueryParam['city'] = city
    //     }
    //     if (district && district != "-1")
    //     {
    //         sql += " and e.district.zoneNumber = :district "
    //         estateQueryParam['district'] = district
    //     }

    //     def countSql = " select count(e.id) from Account e where e.type.code = 'evaluateAccountIndex' and e.bankAccount in " + Account.FilterAccountSql(user)
    //     countSql += sql

    //     if (order && sort)
    //     {
    //         sql += " order by e.${sort} ${order}"
    //     }
    //     else
    //     {
    //         sql += " order by e.modifiedDate desc "
    //     }
    //     estateSql += sql
    //     def accountList = Account.executeQuery(estateSql, estateQueryParam, [max: max, offset: offset])
    //     def accountCount = Account.executeQuery(countSql, estateQueryParam)
    //     respond accountList, model: [accountCount: accountCount[0], params: params], view: 'evaluateAccountIndex'
    // }

    /** ------------------------------其他机构 -----------------------------------**/
    def externalAccountIndex()
    {
        def code = params['code']
        def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        def offset = params.offset ? params.offset.toInteger() : 0
        def name = params["name"]
        def contact = params["contact"]
        def phone = params["phone"]
        def city = params['city']
        def district = params['district']
        def operatingState = params['operatingState']
        def fullName = params['fullName']
        def stage = params['stage']
        def status = params['status']
        def estateQueryParam = new HashMap()
        def sort = params["sort"]
        def order = params["order"]

        def user = User.findById(springSecurityService.principal.id)
        def estateSql = " from Account e where e.type.code = ${code} and e.bankAccount in " + Account.FilterAccountSql(user)
        def sql = " "
        if (name)
        {
            sql += " and e.name like :name"
            estateQueryParam['name'] = '%' + name + '%'
        }
        if (contact)
        {
            sql += " and e.contact like :contact"
            estateQueryParam['contact'] = '%' + contact + '%'
        }
        if (phone)
        {
            sql += " and e.phone like :phone"
            estateQueryParam['phone'] = phone
        }
        if (city && city != "-1")
        {
            sql += " and e.city.zoneNumber = :city"
            estateQueryParam['city'] = city
        }
        if (district && district != "-1")
        {
            sql += " and e.district.zoneNumber = :district"
            estateQueryParam['district'] =  district
        }
        if (operatingState)
        {
            sql += " and e.operatingState = :operatingState"
            estateQueryParam['operatingState'] =  operatingState
        }
        if (fullName)
        {
            sql += " and e.fullName = :fullName"
            estateQueryParam['fullName'] =  fullName
        }
        if (stage)
        {
            sql += " and e.stage.id = :stage"
            estateQueryParam['stage'] =  Long.parseLong(stage)
        }
        if (status)
        {
            sql += " and e.status = :status"
            estateQueryParam['status'] =  status?.toInteger()
        }

        def countSql = " select count(e.id) from Account e where e.type.code = ${code} and e.bankAccount in " + Account.FilterAccountSql(user)
        countSql += sql

        if (order && sort)
        {
            sql += " order by e.${sort} ${order}"
        }
        else
        {
            sql += " order by e.modifiedDate desc "
        }
        estateSql += sql
        def accountList = Account.executeQuery(estateSql, estateQueryParam, [max: max, offset: offset])
        def accountCount = Account.executeQuery(countSql, estateQueryParam)

        def districtList = District.findAllByParentAreaAndAreaLevel(City.findByZoneNumberAndAreaLevel(city, 2), 3)

        respond accountList, model: [accountCount: accountCount[0], code:code, districtList: districtList], view: 'externalAccountIndex'
    }

    def externalAccountCreate()
    {
        respond new Account(params),params["code",params['code']]
    }

    @Transactional
    def externalAccountSave(Account account)
    {
        def type = params['code']
        if(type)
        {
            account.type = AccountTypeDict.findByCode(type)
        }

        if (account == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (account.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond account.errors, view: 'externalAccountCreate'
            return
        }

        account.save flush: true

        redirect (action: 'externalAccountIndex',params:[code:params['code']] )
    }

    def externalAccountEdit(Account account)
    {
        respond account,params["code",params['code']]
    }

    def externalAccountEditDetail(Account account)
    {
        params.targetUri = request.getHeader("referer")
        respond account
    }

    @Transactional
    def externalAccountUpdate(Account account)
    {
        account.save flush: true
        redirect(uri:params["targetUri"] )
    }

    def externalAccountShow(Account account)
    {
        //开发商负面信息
        def companyInfo = developerApiService.getOrginInfo(account?.name)
      //  println "companyInfo--" + companyInfo
        def baseInfo
        if(companyInfo?.企业工商精确?.gsname  && companyInfo?.企业工商精确?.gsname[0]?.gsurl?.gscontent?.jiben ){
            baseInfo = companyInfo?.企业工商精确?.gsname[0]?.gsurl?.gscontent?.jiben[0]
        }
      //  println "baseInfo-->>"+baseInfo

        println "start"
        def inf = new HashMap<String,String>()
        inf.put("companyName",account?.name)

        //处理负面信息
        List<Map<String,String>> list = new ArrayList<HashMap<String,String>>()

        //执行金额
        def zhixingMoney = 0
        //欠税金额
        def qianshuiMoney = 0
        //失信被执行金额
        def shixinMoney = 0
        //欠款欠税金额
        def qiankuanMoney = 0
        //被裁判金额
        def caipanMoney = 0

        //民事审批被告记录
        def shenpanCount = 0
        //那种是否正常
        boolean  isNormal = true
        //被限制出境人数
        def xianchuCount  = 0
        //被限制高消费人数
        def xiangaoCount = 0
        //行政违法记录
        def weifaCount = 0
        //犯罪嫌疑人
        def fanzuiCount = 0


        //执行公开信息
        companyInfo?.企业单笔精确?.fxcontent?.zhixing?.each{
            zhixingMoney += it?.money ? Double.parseDouble(it?.money):0
            Map map = new HashMap()
            map.put("type","执行公开信息")
            map.put("name",it?.name)
            map.put("money",it?.money)
            map.put("content",it?.content)
            map.put("state",it?.state)
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //失信被执行信息
        companyInfo?.企业单笔精确?.fxcontent?.shixin?.each{
            shixinMoney += it?.money ? Double.parseDouble(it?.money):0
            Map map = new HashMap()
            map.put("type","失信被执行信息")
            map.put("name",it?.name)
            map.put("money",it?.wlmoney)
            map.put("content",it?.content)
            map.put("state",it?.state)
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //限制高消费记录
        companyInfo?.企业单笔精确?.fxcontent?.xiangao?.each{
            xiangaoCount++
            Map map = new HashMap()
            map.put("type","限制高消费记录")
            map.put("name",it?.name)
            map.put("money","--")
            map.put("content",it?.content)
            map.put("state",it?.state)
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //限制出入境记录
        companyInfo?.企业单笔精确?.fxcontent?.xianchu?.each{
            xianchuCount++
            Map map = new HashMap()
            map.put("type","限制出入境记录")
            map.put("name",it?.name)
            map.put("money","--")
            map.put("content",it?.content)
            map.put("state",it?.state)
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //民事裁判记录
        companyInfo?.企业单笔精确?.fxcontent?.caipan?.each{
            caipanMoney += it?.money ? Double.parseDouble(it?.money):0
            Map map = new HashMap()
            map.put("type","民事裁判记录")
            map.put("name",it?.name)
            map.put("money",it?.money)
            map.put("content",it?.content)
            map.put("state","--")
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //民事审判记录
        companyInfo?.企业单笔精确?.fxcontent?.shenpan?.each{
            shenpanCount++
            Map map = new HashMap()
            map.put("type","民事审判记录")
            map.put("name",it?.name)
            map.put("money","--")
            map.put("content",it?.content)
            map.put("state","--")
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //罪犯及嫌疑人记录
        companyInfo?.企业单笔精确?.fxcontent?.zuifan?.each{
            fanzuiCount++
            Map map = new HashMap()
            map.put("type","罪犯及嫌疑人记录")
            map.put("name",it?.name)
            map.put("money","--")
            map.put("content",it?.content)
            map.put("state","--")
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //行政违法记录
        companyInfo?.企业单笔精确?.fxcontent?.weifa?.each{
            weifaCount++
            Map map = new HashMap()
            map.put("type","行政违法记录")
            map.put("name",it?.name)
            map.put("money","--")
            map.put("content",it?.content)
            map.put("state","--")
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //欠税名单
        companyInfo?.企业单笔精确?.fxcontent?.qianshui?.each{
            qianshuiMoney += it?.money ? Double.parseDouble(it?.money):0
            Map map = new HashMap()
            map.put("type","欠税名单")
            map.put("name",it?.name)
            map.put("money",it?.money)
            map.put("content",it?.taxperiod)
            map.put("state","--")
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //纳税非正常户
        companyInfo?.企业单笔精确?.fxcontent?.feizheng?.each{
            isNormal = false
            Map map = new HashMap()
            map.put("type","纳税非正常户")
            map.put("name",it?.name)
            map.put("money","--")
            map.put("content",it?.title)
            map.put("state","--")
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //欠款欠费名单
        companyInfo?.企业单笔精确?.fxcontent?.qiankuan?.each{
            qiankuanMoney += it?.money ? Double.parseDouble(it?.money):0
            Map map = new HashMap()
            map.put("type","欠款欠费名单")
            map.put("name",it?.name)
            map.put("money",it?.money)
            map.put("content",it?.title)
            map.put("state","--")
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        list.each {
            it?.content = it.content.replace("<p>","").replace("</p>","")
        }

        respond account, model: [params: params,zhixingMoney:(zhixingMoney/10000).toInteger(),
                                 qianshuiMoney:(qianshuiMoney/10000).toInteger(),shixinMoney:(shixinMoney/10000).toInteger(),qiankuanMoney:(qiankuanMoney/10000).toInteger(),
                                 caipanMoney:(caipanMoney/10000).toInteger(),shenpanCount:shenpanCount,isNormal:isNormal,xianchuCount:xianchuCount,xiangaoCount:xiangaoCount,
                                 weifaCount:weifaCount,fanzuiCount:fanzuiCount,fumianList:list], view: 'externalAccountShow'
    }

    @Transactional
    def delete(Account account)
    {

        if (account == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        account.delete flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'account.label', default: 'account'), account.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NO_CONTENT }
        }
    }

    // *********************************银行机构*********************************

    def accountIndex(Integer max)
    {

        def accountImport = false
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        // 总行机构，无下属机构，显示添加机构功能
        if (user?.account?.level?.code == "0" && !Account.findAllByParent(user?.account))
        {
            accountImport = true
        }

        params.max = Math.min(max ?: 10, 100)
        respond new Account(), model: [accountCount: Account.count(), accountImport: accountImport]
    }

    @Transactional
    def accountSave(Account account)
    {
        println account?.errors
        if (account == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (account.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond account.errors, view: 'accountIndex'
            return
        }

        account.type = AccountTypeDict.BANK()
        if (account.validate())
        {
            account.save flush: true
        }
        else
        {
            println account.errors
        }

        // 新增
        if (!params["id"])
        {
            // 递归查出所有上级机构（包括自己）
            def accountList = accountService.getAllParent(account, [])
            accountList?.each {
                def accountManageAccount = new AccountManageAccount()
                accountManageAccount.account = it
                accountManageAccount.manageAccount = account
                accountManageAccount.save()
            }
        }

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'account.label', default: 'Account'), account.id])
                redirect action: 'accountIndex'
            }
            '*' { respond account, [status: CREATED] }
        }
    }

    def getAllAccountList()
    {
        def sql = "select new map(o.id as id, o.parent.id as pId, o.name as name) from Account o where o.type.code = 'BankAccount'"
        def name = params['name']
        if (name)
        {
            sql += " and o.name like '%${name}%'"
        }
        sql += " order by level, name"

        def accountList = Account.executeQuery(sql).asList()
        render([status: "success", accountList: accountList] as JSON)
    }

    @Transactional
    def editAccount()
    {
        def id = params["id"]
        def name = params["name"]
        if (!id || !name)
        {
            render([message: "参数信息不全，请重试", status: "Failed"] as JSON)
            return
        }

        def account = Account.findById(id)
        account.name = name
        if (account.validate())
        {
            account.save flush: true
        }
        else
        {
            println account.errors
        }

        render([status: "success"] as JSON)
    }

    @Transactional
    def addAccount()
    {
        def pId = params["pId"]

        def account = new Account()
        account.name = "new node"
        account.parent = Account.findById(pId)
        if (account.validate())
        {
            account.save flush: true
        }
        else
        {
            println account.errors
        }

        // 递归查出所有上级机构（包括自己）
        def accountList = accountService.getAllParent(account, [])
        accountList?.each {
            def accountManageAccount = new AccountManageAccount()
            accountManageAccount.account = it
            accountManageAccount.manageAccount = account
            accountManageAccount.save()
        }

        render([status: "success", account: account] as JSON)
    }

    @Transactional
    def deleteAccount()
    {
        def id = params["id"]
        def account = Account.findById(id)

        def accountManageAccountList = AccountManageAccount.findAll("from AccountManageAccount as o where o.account.id = ${id} or o.manageAccount.id = ${id}")
        accountManageAccountList?.each {
            it?.delete flush: true
        }

        account.delete flush: true

        render([status: "success"] as JSON)
    }

    def queryAccountById()
    {
        def id = params["id"]
        def account = Account.findById(id)
        render([status: "success", account: account] as JSON)
    }

    def queryAllAccountManageById()
    {
        def id = params["id"]
        def resultList = AccountManageAccount.findAllByAccount(Account.findById(id))

        def accountManageList = []
        def sql = "select new map(o.id as id, o.parent.id as pId, o.name as name) from Account o where o.type.code = 'BankAccount' order by level, name"
        def accountList = Account.executeQuery(sql).asList()
        accountList?.each {
            if (it?.id in resultList*.manageAccount.id)
            {
                def item = [id: it?.id, pId: it?.pId, name: it?.name, checked: true, open: true]
                accountManageList.add(item)
            }
            else
            {
                def item = [id: it?.id, pId: it?.pId, name: it?.name, checked: false, open: true]
                accountManageList.add(item)
            }
        }
        render([status: "success", accountManageList: accountManageList] as JSON)
    }

    @Transactional
    def addAccountManageAccount()
    {
        def id = params["id"]
        def manageId = params["manageId"]
        def flag = params["flag"]

        def account = Account.findById(id)
        def manageAccount = Account.findById(manageId)

        if (flag == "true")
        {
            // 添加权限
            def accountManageAccount = new AccountManageAccount()
            accountManageAccount.account = account
            accountManageAccount.manageAccount = manageAccount
            accountManageAccount.save flush: true

            render([status: "success"] as JSON);
        }
        else
        {
            // 删除权限
            def accountManageAccount = AccountManageAccount.findByAccountAndManageAccount(account, manageAccount)
            accountManageAccount?.delete flush: true

            render([status: "success"] as JSON)
        }
    }

    def accountDataMigration(Integer max)
    {
        params.max = Math.min(max ?: 10, 100)
        params.sort = "modifiedDate"
        params.order = "desc"
        respond Account.list(params), model: [accountCount: Account.count()]
    }

    // 数据迁移页面搜索
    def searchAccountData()
    {
        params.max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        params.offset = params.offset ? params.offset.toInteger() : 0;

        def name = params["name"]
        def contact = params["contact"]
        def phone = params["phone"]
        def cellphone = params["cellphone"]

        String sql = "from Account as o where 1=1"
        if (name)
        {
            sql += " and o.name like '%${name}%'"
        }
        if (contact)
        {
            sql += " and o.contact like '%${contact}%'"
        }
        if (phone)
        {
            sql += " and o.phone like '%${phone}%'"
        }
        if (cellphone)
        {
            sql += " and o.cellphone like '%${cellphone}%'"
        }
        sql += ' order by modifiedDate desc'

        println "sql:" + sql

        def max = params.max
        def offset = params.offset

        def list = Account.findAll(sql, [max: max, offset: offset])
        def list1 = Account.findAll(sql)
        def count = list1.size()

        respond list, model: [accountCount: count, params: params], view: 'accountDataMigration'
    }

    @Transactional
    def dataMigration()
    {
        def oldAccountId = params["oldAccountId"]
        def newAccountId = params["newAccountId"]

        def oldAccount = Account.findById(oldAccountId)
        if (!oldAccountId || !oldAccount)
        {
            flash.message = "迁移失败，请重试！"
            redirect action: 'accountDataMigration'
        }
        def newAccount = Account.findById(newAccountId)
        if (!newAccountId || !newAccount)
        {
            flash.message = "迁移失败，请重试！"
            redirect action: 'accountDataMigration'
        }

        def estateList = Estate.findAllByAccount(oldAccount)
        estateList?.each {
            it?.account = newAccount
            it?.save()
        }

        redirect action: 'accountDataMigration'
    }

    @Transactional
    def accountCsvImport()
    {
        // 读取文件
        def file = request.getFile('myFile')
        def fileCharset = FileUtil.GetFileCharset(file.getInputStream())
        def status = "success"

        //将文件传给对应类,读取文件
        try
        {
            def importer = new AccountCSVImporter()
            def estateMapList = importer.read(file.getInputStream(), fileCharset)
            accountService.accountInserts(estateMapList)
        }
        catch (Exception e)
        {
            status = "failed"
            println e.printStackTrace()
        }

        redirect action: 'index', params: [status: status]
    }

    /*
    * 获取zoneNumber
    * */

    def getZoneNumber()
    {
        def db = new groovy.sql.Sql(dataSource)
        def id = params['id'];
        def sql = "SELECT * FROM area A WHERE area_id = " + id
        def result = db.rows(sql).asList()
        db.close()
        render([result: result] as JSON)
    }

    def getAccountList()
    {
        def city = params['city']
        def name = params['name']
        def user = User.findById(springSecurityService.principal.id)
        def result = Account.executeQuery("select new map(o.id as id, o.name as name, o.address as address, o.x as x, o.y as y) from Account o where o.city.zoneNumber = '${city}' and o.type.code = 'BankAccount' and o.name like '%${name}%'and o.id in " + Account.FilterAccountSql(user)).asList()
        render([result: result] as JSON)
    }

    /******************************机构清退***********************************************/

    def retreatAccountEdit(Account account){

        params.targetUri = request.getHeader("referer")
        respond account
    }

    @Transactional
    def retreatAccountUpdate(Account account)
    {
        def date = account.retreatDate
        if(!date){
            date = new Date()
            account.retreatDate = date
        }

        if (account == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (account.hasErrors())
        {
            println account.errors
            transactionStatus.setRollbackOnly()
            respond account.errors, view: 'retreatAccountEdit'
            return
        }

        account.save flush: true

        redirect(uri: params["targetUri"])
    }

    //初始化机构清退审批工作流
    def initRetreatAccountWorkflow(Account account){

        def workflow = account.retreatWorkflow
        accountService.initAccountFlowStage(account, workflow)

        redirect action: 'externalAccountShow', id: account?.id, params: [code: params.code]
    }

    def accountPendingShow(WorkflowInstance workflowInstance)
    {
        def account = workflowInstance?.account
        def user = User.findById(springSecurityService.principal.id)
        def flowStage = workflowInstance?.stage
        def editRoleFlag = false
        def approveRoleFlag = false
        if (flowStage)
        {
            editRoleFlag = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.id = ? and authority.id = ? and user.id = ? ", [flowStage?.id, WorkflowAuthority.EDIT()?.id,user?.id]) && true
            approveRoleFlag = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.id = ? and authority.id = ? and user.id = ? " , [flowStage?.id, WorkflowAuthority.APPROVAL()?.id,user?.id]) && true
        }
        def layout = flowStage?.layout?.name

        //开发商负面信息
        def companyInfo = developerApiService.getOrginInfo(account?.name)
        //  println "companyInfo--" + companyInfo
        def baseInfo
        if(companyInfo?.企业工商精确?.gsname  && companyInfo?.企业工商精确?.gsname[0]?.gsurl?.gscontent?.jiben ){
            baseInfo = companyInfo?.企业工商精确?.gsname[0]?.gsurl?.gscontent?.jiben[0]
        }
        //  println "baseInfo-->>"+baseInfo

        println "start"
        def inf = new HashMap<String,String>()
        inf.put("companyName",account?.name)

        //处理负面信息
        List<Map<String,String>> list = new ArrayList<HashMap<String,String>>()

        //执行金额
        def zhixingMoney = 0
        //欠税金额
        def qianshuiMoney = 0
        //失信被执行金额
        def shixinMoney = 0
        //欠款欠税金额
        def qiankuanMoney = 0
        //被裁判金额
        def caipanMoney = 0

        //民事审批被告记录
        def shenpanCount = 0
        //那种是否正常
        boolean  isNormal = true
        //被限制出境人数
        def xianchuCount  = 0
        //被限制高消费人数
        def xiangaoCount = 0
        //行政违法记录
        def weifaCount = 0
        //犯罪嫌疑人
        def fanzuiCount = 0


        //执行公开信息
        companyInfo?.企业单笔精确?.fxcontent?.zhixing?.each{
            zhixingMoney += it?.money ? Double.parseDouble(it?.money):0
            Map map = new HashMap()
            map.put("type","执行公开信息")
            map.put("name",it?.name)
            map.put("money",it?.money)
            map.put("content",it?.content)
            map.put("state",it?.state)
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //失信被执行信息
        companyInfo?.企业单笔精确?.fxcontent?.shixin?.each{
            shixinMoney += it?.money ? Double.parseDouble(it?.money):0
            Map map = new HashMap()
            map.put("type","失信被执行信息")
            map.put("name",it?.name)
            map.put("money",it?.wlmoney)
            map.put("content",it?.content)
            map.put("state",it?.state)
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //限制高消费记录
        companyInfo?.企业单笔精确?.fxcontent?.xiangao?.each{
            xiangaoCount++
            Map map = new HashMap()
            map.put("type","限制高消费记录")
            map.put("name",it?.name)
            map.put("money","--")
            map.put("content",it?.content)
            map.put("state",it?.state)
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //限制出入境记录
        companyInfo?.企业单笔精确?.fxcontent?.xianchu?.each{
            xianchuCount++
            Map map = new HashMap()
            map.put("type","限制出入境记录")
            map.put("name",it?.name)
            map.put("money","--")
            map.put("content",it?.content)
            map.put("state",it?.state)
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //民事裁判记录
        companyInfo?.企业单笔精确?.fxcontent?.caipan?.each{
            caipanMoney += it?.money ? Double.parseDouble(it?.money):0
            Map map = new HashMap()
            map.put("type","民事裁判记录")
            map.put("name",it?.name)
            map.put("money",it?.money)
            map.put("content",it?.content)
            map.put("state","--")
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //民事审判记录
        companyInfo?.企业单笔精确?.fxcontent?.shenpan?.each{
            shenpanCount++
            Map map = new HashMap()
            map.put("type","民事审判记录")
            map.put("name",it?.name)
            map.put("money","--")
            map.put("content",it?.content)
            map.put("state","--")
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //罪犯及嫌疑人记录
        companyInfo?.企业单笔精确?.fxcontent?.zuifan?.each{
            fanzuiCount++
            Map map = new HashMap()
            map.put("type","罪犯及嫌疑人记录")
            map.put("name",it?.name)
            map.put("money","--")
            map.put("content",it?.content)
            map.put("state","--")
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //行政违法记录
        companyInfo?.企业单笔精确?.fxcontent?.weifa?.each{
            weifaCount++
            Map map = new HashMap()
            map.put("type","行政违法记录")
            map.put("name",it?.name)
            map.put("money","--")
            map.put("content",it?.content)
            map.put("state","--")
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //欠税名单
        companyInfo?.企业单笔精确?.fxcontent?.qianshui?.each{
            qianshuiMoney += it?.money ? Double.parseDouble(it?.money):0
            Map map = new HashMap()
            map.put("type","欠税名单")
            map.put("name",it?.name)
            map.put("money",it?.money)
            map.put("content",it?.taxperiod)
            map.put("state","--")
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //纳税非正常户
        companyInfo?.企业单笔精确?.fxcontent?.feizheng?.each{
            isNormal = false
            Map map = new HashMap()
            map.put("type","纳税非正常户")
            map.put("name",it?.name)
            map.put("money","--")
            map.put("content",it?.title)
            map.put("state","--")
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //欠款欠费名单
        companyInfo?.企业单笔精确?.fxcontent?.qiankuan?.each{
            qiankuanMoney += it?.money ? Double.parseDouble(it?.money):0
            Map map = new HashMap()
            map.put("type","欠款欠费名单")
            map.put("name",it?.name)
            map.put("money",it?.money)
            map.put("content",it?.title)
            map.put("state","--")
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        list.each {
            it?.content = it.content.replace("<p>","").replace("</p>","")
        }

        respond account, model: [workflowInstance: workflowInstance, editRoleFlag: editRoleFlag, approveRoleFlag: approveRoleFlag, params: params,zhixingMoney:(zhixingMoney/10000).toInteger(),
                                 qianshuiMoney:(qianshuiMoney/10000).toInteger(),shixinMoney:(shixinMoney/10000).toInteger(),qiankuanMoney:(qiankuanMoney/10000).toInteger(),
                                 caipanMoney:(caipanMoney/10000).toInteger(),shenpanCount:shenpanCount,isNormal:isNormal,xianchuCount:xianchuCount,xiangaoCount:xiangaoCount,
                                 weifaCount:weifaCount,fanzuiCount:fanzuiCount,fumianList:list], view: layout
    }
}
